package com.laotang.第_15_章_图论算法.图的DFS和BFS;

import java.util.*;

public class Graph_BFS {


    class TreeNode {
        int val;
        List<TreeNode> children;

        TreeNode(int val) {
            this.val = val;
            this.children = new ArrayList<>();
        }
    }

    // 1. N 叉树的层序遍历
    public void bfs(TreeNode root) {
        if (root == null) return;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode curr = queue.poll();
            System.out.println(curr.val);
            for (TreeNode child : curr.children) {
                queue.offer(child);
            }
        }
    }

    private static class Node {
        int val;
        List<Node> neighbors;

        public Node(int val) {
            val = val;
            neighbors = new ArrayList<Node>();
        }
    }

    // 图的广度优先遍历
    Set<Node> visited = new HashSet<>();
    public void bfs(Node node) {
        if (node == null) return;

        Queue<Node> queue = new LinkedList<>();
        queue.offer(node);
        while (!queue.isEmpty()) {
            Node curr = queue.poll();
            System.out.println(curr.val);
            visited.add(curr);
            for (Node neighbor : curr.neighbors) {
                if (!visited.contains(neighbor)) queue.offer(neighbor);
            }
        }
    }
}
